package qeug.shsh.facde.controller;

import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.operate.result.IOperateInfo;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.openapi.common.custom.annotation.ApiController;
import kd.bos.openapi.common.custom.annotation.ApiPostMapping;
import kd.bos.openapi.common.custom.annotation.ApiRequestBody;
import kd.bos.openapi.common.custom.annotation.ApiResponseBody;
import kd.bos.openapi.common.result.CustomApiResult;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import qeug.shsh.facde.info.AuditData;
import qeug.shsh.facde.info.AuditModel;
import qeug.shsh.helper.FacadeHelper;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

/**
 * @projectName: qeug-cosmic-root-project
 * @package: qeug.shsh.facde.controller
 * @className: ApprovalResultController
 * @author: wenyx
 * @description: TODO
 * @date: 2023/10/23 11:00
 * @version: 1.0
 * 说明：费用报销单、预算调整单、差旅报销单BPM审批回传接口
 */
@ApiController(value = "ApprovalResultController", desc = "结果回传接口")
public class ApprovalResultController implements Serializable {

    @ApiPostMapping(value = "/ApprovalResult", desc = "结果回传接口")
    public CustomApiResult<@ApiResponseBody("返回参数") String> result_audit
            (@NotNull @Valid @ApiRequestBody(value = "入参") AuditModel auditModel) throws ParseException {
        CustomApiResult auditApiResultExt = new CustomApiResult();
        OperateOption operateOption = OperateOption.create();
        operateOption.setVariableValue("ignoreValidation", String.valueOf(true));//绕过网络互斥操作
        String isfull = auditModel.getIsfull();

        ArrayList<AuditData> data = auditModel.getData();
        int i = 0; //通过标识判断是否有全量
        for (AuditData auditData : data) {
            if (i != 0) {
                isfull = "0";
                i = i + 1;
            }
            HashMap<String, Object> auditLog = new HashMap<>();
            String strProcessName = auditData.getStrProcessName(); // 流程名
            String applicationNo = auditData.getApplicationNo(); // 单据编号
            int incident = auditData.getIncident(); // 实例号
            String aprUserID = auditData.getAprUserID(); // 审批人工号
            String aprUserName = auditData.getAprUserName(); // 审批人名称
            String stepName = auditData.getStepName(); // 审批岗位
            String aprStatus = auditData.getAprStatus(); // 审批状态
            String aprResult = auditData.getAprResult(); // 审批意见
            String aprTm = auditData.getAprTm(); // 审批时间
            String nextAprUserID = auditData.getNextAprUserID(); // 下一节点审批人工号
            String nextAprUserName = auditData.getNextAprUserName(); // 下一节点审批人姓名
            String completed = auditData.getCompleted(); // 是否审批结束

            String entityName = null;
            switch (strProcessName) {
                case "CCS费用报销单":
                    entityName = "er_dailyreimbursebill";
                    break;
                case "CCS预算调整流程":
                    entityName = "bgm_adjustbill";
                    break;
                case "CCS差旅报销单":
                    entityName = "er_tripreimbursebill";
                    break;
            }
            //单据信息：通过编码和实例号查询单据信息
            QFilter[] a = new QFilter[]{new QFilter("billno", "=", applicationNo)
                    , new QFilter("qeug_processinstance", "=", Integer.toString(incident))};//单据信息：通过编码和实例号查询单据信息
            DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(entityName, a);
            if (dynamicObject == null) {
                //找不到对应的单据
                auditApiResultExt.setErrorCode("500");
                auditApiResultExt.setStatus(false);
                auditApiResultExt.setMessage("找不到对应的单据！");
                return auditApiResultExt;
            }

            //是否审批结束，来判断。是否调用审批结束操作
            Boolean iscompleted = false;//是否审批结束判断
            //记录审批日志
            if (aprTm.equals("")) {
                auditLog.put("apptime", "");
            } else {
                Date date = new Date(aprTm);
                auditLog.put("apptime", date);
            }
            auditLog.put("billno", applicationNo);
            auditLog.put("sourcesystem", "BPM");
            auditLog.put("approvernum", aprUserID);
            auditLog.put("approvername", aprUserName);
            auditLog.put("stepwame", stepName);
            auditLog.put("appopinion", aprResult);
            auditLog.put("appresult", aprStatus);
            auditLog.put("nextapruserld", nextAprUserID);
            auditLog.put("nextaprusername", nextAprUserName);
            auditLog.put("bpmid", Integer.toString(incident));

            if ("0".equals(completed)) {
                //单次审批结束
                auditLog.put("islast", iscompleted);//是否审批结束-否
                if ("通过".equals(aprStatus)) {
                    //单次审批结束，记录单次审批通过日志
                    FacadeHelper.addAduitLog(auditLog, isfull);
                } else if ("驳回".equals(aprStatus)) {
                    //如果不通过，单据状态变为保存（撤销），后续用户再次提交
                    dynamicObject.set("qeug_processinstance", "");//bpm流程实例清空
                    OperationResult unSubmit = SaveServiceHelper.saveOperate("noapprive", entityName, new DynamicObject[]{dynamicObject}, operateOption);//调用审核不通过操作
                    boolean success = unSubmit.isSuccess();
                    if (success) {
                        //记录审批日志
                        FacadeHelper.addAduitLog(auditLog, isfull);
                    } else {
                        //如果撤销失败，输出错误原因
                        String message = null;
                        for (IOperateInfo errInfo : unSubmit.getAllErrorOrValidateInfo()) {
                            message = errInfo.getMessage();
                        }
                        auditApiResultExt.setErrorCode("500");
                        auditApiResultExt.setStatus(false);
                        auditApiResultExt.setMessage(message);

                        return auditApiResultExt;
                    }
                }
            } else if ("1".equals(completed)) {
                //最终审批结果回传
                iscompleted = true;
                auditLog.put("islast", iscompleted);//是否审批结束-是
                if ("通过".equals(aprStatus) || "".equals(aprStatus)) {
                    //最终审批通过，调用审核操作
                    OperationResult audit = OperationServiceHelper.executeOperate("audit", entityName, new DynamicObject[]{dynamicObject}, operateOption);//调用审核操作
                    boolean success = audit.isSuccess();
                    if (success) {
                        //记录最终成功审批日志
                        FacadeHelper.addAduitLog(auditLog, isfull);
                        QFilter[] a1 = new QFilter[]{new QFilter("billno", "=", applicationNo)};//单据信息：通过编码和实例号查询单据信息
                        DynamicObject dynamicObject1 = BusinessDataServiceHelper.loadSingle(entityName, a1);
                        if (entityName != null && entityName.equals("er_dailyreimbursebill")) {
                            //费用报销单，单独验证是否为冲借款
                            DynamicObjectCollection writeoffmoneyCollection = dynamicObject1.getDynamicObjectCollection("writeoffmoney");//冲借款
                            DynamicObjectCollection accountentryCollection = dynamicObject1.getDynamicObjectCollection("accountentry");//收款信息
                            DynamicObject accountentry = accountentryCollection.get(0);
                            BigDecimal orireceiveamount = accountentry.getBigDecimal("orireceiveamount");//收款金额
                            if (writeoffmoneyCollection.size() > 0 || orireceiveamount.compareTo(BigDecimal.ZERO) == 0) {
                                //冲借款的费用报销单审核通过后不推送G6，直接变为已付款
                                dynamicObject.set("head_paydate", new Date());//付款日期
                                dynamicObject.set("billstatus", "G");//单据状态
                                SaveServiceHelper.saveOperate(entityName, new DynamicObject[]{dynamicObject}, OperateOption.create());

                                String id1 = String.valueOf(dynamicObject.get("id"));
                                OperationServiceHelper.executeOperate("generatevoucher", "er_dailyreimbursebill", new Object[]{id1}, operateOption);//调用生成凭证操作

                                auditApiResultExt.setStatus(true);
                                auditApiResultExt.setErrorCode("200");
                                auditApiResultExt.setMessage("操作成功");
                                return auditApiResultExt;
                            }
                        }
                        boolean qeug_istog6 = dynamicObject1.getBoolean("qeug_istog6");//是否传至G6
                        //审核通过的单据直接变为等待付款(除去预算调整单)
                        if (entityName != null && !entityName.equals("bgm_adjustbill") && qeug_istog6) {
                            //差旅报销单、费用报销单在推送G6成功后再变为等待付款
                            dynamicObject.set("billstatus", "F");//单据状态
                        }
                        SaveServiceHelper.saveOperate(entityName, new DynamicObject[]{dynamicObject}, OperateOption.create());
                        if (!qeug_istog6) {
                            auditApiResultExt.setStatus(true);
                            auditApiResultExt.setErrorCode("200");
                            auditApiResultExt.setMessage("操作成功,BPM审批流程结束,但单据推送G6失败,请联系开发人员进行排查！");

                            return auditApiResultExt;
                        }
                    } else {
                        //如果审核不成功，输出错误原因
                        String message = null;
                        for (IOperateInfo errInfo : audit.getAllErrorOrValidateInfo()) {
                            message = errInfo.getMessage();
                        }
                        auditApiResultExt.setErrorCode("500");
                        auditApiResultExt.setStatus(false);
                        auditApiResultExt.setMessage(message);

                        return auditApiResultExt;
                    }
                } else if ("驳回".equals(aprStatus)) {
                    //如果不通过，单据状态变为保存（撤销），后续用户再次提交
                    dynamicObject.set("qeug_processinstance", "");//bpm流程实例清空
                    OperationResult unSubmit = SaveServiceHelper.saveOperate("noapprive", entityName, new DynamicObject[]{dynamicObject}, operateOption);//调用审核不通过操作
                    boolean success = unSubmit.isSuccess();
                    if (success) {
                        //记录审批日志
                        FacadeHelper.addAduitLog(auditLog, isfull);
                    } else {
                        //如果不成功，输出错误原因
                        String message = null;
                        for (IOperateInfo errInfo : unSubmit.getAllErrorOrValidateInfo()) {
                            message = errInfo.getMessage();
                        }
                        auditApiResultExt.setErrorCode("500");
                        auditApiResultExt.setStatus(false);
                        auditApiResultExt.setMessage(message);

                        return auditApiResultExt;
                    }
                }
            }
        }

        //中途未不成功，便返回成功结果
        auditApiResultExt.setStatus(true);
        auditApiResultExt.setErrorCode("200");
        auditApiResultExt.setMessage("操作成功");

        return auditApiResultExt;
    }
}
